<template>
  <div class="historical-position-container">
    <!-- 操作按钮区域 -->
    <div class="position-actions">
      <el-button type="primary" @click="handleAddPosition" icon="el-icon-plus">
        添加图片
      </el-button>
      
      <!-- 排序功能 -->
      <div class="sort-controls">
        <span class="sort-label">排序方式:</span>
        <el-select v-model="sortType" @change="handleSortChange" size="small" style="width: 120px; margin-right: 10px;" title="选择排序方式">
          <el-option label="日期" value="date"></el-option>
          <el-option label="创建日期" value="createdTime"></el-option>
          <el-option label="总市值" value="totalValue"></el-option>
          <el-option label="总股数" value="totalCount"></el-option>
        </el-select>
        
        <el-button-group>
          <el-button 
            :type="sortOrder === 'desc' ? 'primary' : 'default'" 
            size="small" 
            icon="el-icon-sort-down"
            @click="setSortOrder('desc')"
            title="降序排列"
          >
            降序
          </el-button>
          <el-button 
            :type="sortOrder === 'asc' ? 'primary' : 'default'" 
            size="small" 
            icon="el-icon-sort-up"
            @click="setSortOrder('asc')"
            title="升序排列"
          >
            升序
          </el-button>
        </el-button-group>
        
        <!-- 帮助提示 -->
         <el-tooltip content="快捷键: Ctrl+1/2/3切换排序类型，Ctrl+↑/↓切换排序顺序" placement="top">
           <i class="el-icon-question" style="margin-left: 8px; color: #909399; cursor: help;"></i>
         </el-tooltip>
         
         <!-- 重置排序 -->
         <el-button 
           type="text" 
           size="mini" 
           icon="el-icon-refresh"
           @click="resetSort"
           title="重置为默认排序"
           style="margin-left: 8px; color: #909399;"
         >
           重置
         </el-button>
      </div>
      <!-- 排序状态标签 -->
      <div class="sort-status" v-if="positionList.length > 0">
      <el-tag size="small" type="info" :effect="loading ? 'dark' : 'light'">
        <i :class="loading ? 'el-icon-loading' : 'el-icon-sort'"></i>
        {{ getSortTypeLabel(sortType) }} · {{ sortOrder === 'desc' ? '降序' : '升序' }}
        <span style="margin-left: 8px; opacity: 0.8;">({{ positionList.length }}条)</span>
      </el-tag>
    </div>
    </div>

    <!-- 图片展示区域 -->
    <div v-loading="loading" class="position-images">
      <el-empty v-if="positionList.length === 0" description="暂无历史持仓图片"></el-empty>
      <el-row v-else :gutter="80">
        <el-col v-for="(item, index) in positionList" :key="item.id" :xs="24" :sm="12" :md="6" :lg="4" :xl="3">
          <div class="position-image-card">
            <el-image
              :src="item.imageBase64"
              fit="contain"
              class="position-image"
              @click.stop="handleViewPosition(item)"
              style="cursor: pointer;"
              :lazy="true"
              scroll-container=".position-images"
            >
              <template #error>
                <div class="image-error">
                  <i class="el-icon-picture-outline"></i>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>
            <div class="position-image-info">
              <div class="info-date">{{ formatDate(item.positionDate) }}</div>
              <div class="info-stats">
                <div class="stat-item">
                  <span class="stat-label">总股数:</span>
                  <span class="stat-value">{{ formatNumber(item.positionCount) }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">市值:</span>
                  <span class="stat-value">{{ formatCurrency(item.totalValue) }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">盈亏:</span>
                  <span class="stat-value" :class="{ 'profit-positive': item.totalProfit >= 0, 'profit-negative': item.totalProfit < 0 }">
                    {{ formatCurrency(item.totalProfit) }}
                  </span>
                </div>
              </div>
              <div class="info-actions">
                <el-button type="text" @click.stop="handleViewPosition(item)" icon="el-icon-view">
                  查看
                </el-button>
                <el-button type="text" @click.stop="handleDeletePosition(item)" icon="el-icon-delete" style="color: #f56c6c;">
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 分页区域 -->
    <div class="position-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[8, 16, 24, 32]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
    </div>

    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      multiple
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<script>
import { getHistoricalPositionPage, uploadHistoricalPosition, deleteHistoricalPosition } from '@/api/historicalPosition'

export default {
  name: 'HistoricalPosition',
  props: {
    stockCode: {
      type: String,
      required: true
    },
    stockName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      positionList: [], // 历史持仓图片列表
      currentPage: 1, // 当前页码
      pageSize: 8, // 每页显示数量
      totalCount: 0, // 总数量
      loading: false, // 加载状态
      lastLoadTime: 0, // 上次加载时间，用于防抖
      sortType: 'date', // 排序类型: date-日期, createdTime-创建日期, totalValue-总市值, totalCount-总股数
      sortOrder: 'desc' // 排序顺序: asc-升序, desc-降序
    }
  },
  mounted() {
    // 从本地存储加载排序偏好
    this.loadSortPreferences()
    this.loadPositions()
    // 添加键盘快捷键支持
    this.setupKeyboardShortcuts()
  },
  watch: {
    // 监听props变化，当股票代码或名称改变时重新加载数据
    stockCode(newVal, oldVal) {
      if (newVal !== oldVal && newVal) {
        this.resetAndLoad()
      }
    }
  },
  
  beforeUnmount() {
    // 清理所有异步操作和事件监听器
    this.cleanup()
  },
  
  deactivated() {
    // 组件停用时也进行清理
    this.cleanup()
  },
  
  methods: {
    // 清理函数
    cleanup() {
      // 移除键盘事件监听器
      if (this.handleKeyDown) {
        document.removeEventListener('keydown', this.handleKeyDown)
      }
      
      // 清理任何未完成的异步操作
      this.loading = false
      
      // 清理任何可能存在的消息框实例
      if (this.$message) {
        this.$message.closeAll()
      }
    },
    
    // 重置并重新加载数据
    resetAndLoad() {
      this.currentPage = 1
      this.loadPositions()
    },
    
    // 加载历史持仓数据
    loadPositions() {
      // 检查组件是否仍然有效
      if (this._isDestroyed || this._isBeingDestroyed) {
        return
      }
      
      // 防抖检查：如果300ms内已经调用过，则直接返回
      const now = Date.now()
      if (now - this.lastLoadTime < 300) {
        return
      }
      this.lastLoadTime = now
      
      this.loading = true
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        stockCode: this.stockCode, // 传入股票代码参数
        sortType: this.sortType, // 排序类型
        sortOrder: this.sortOrder // 排序顺序
      }
      
      getHistoricalPositionPage(params).then(response => {
        // 再次检查组件状态
        if (this._isDestroyed || this._isBeingDestroyed) {
          return
        }
        
        console.log('历史持仓数据返回:', response)
        if (response.code === 200 && response.data) {
          this.positionList = response.data.records || []
          this.totalCount = response.data.total || 0
          
          // 调试：检查第一条记录的图片数据
          if (this.positionList.length > 0) {
            console.log('第一条记录数据:', this.positionList[0])
            console.log('第一条记录图片数据是否存在:', !!this.positionList[0].imageBase64)
          }
        } else {
          this.$message.error('获取历史持仓数据失败: ' + response.msg)
          this.positionList = []
          this.totalCount = 0
        }
        this.loading = false
      }).catch(error => {
        // 检查组件状态
        if (this._isDestroyed || this._isBeingDestroyed) {
          return
        }
        
        console.error('获取历史持仓数据时发生错误:', error)
        this.$message.error('获取历史持仓数据时发生错误')
        this.positionList = []
        this.totalCount = 0
        this.loading = false
      })
    },

    // 添加历史持仓图片
    handleAddPosition() {
      // 检查组件是否仍然有效
      if (this._isDestroyed || this._isBeingDestroyed) {
        return
      }
      
      // 首先尝试获取剪贴板中的图片
      if (navigator.clipboard && navigator.clipboard.read) {
        navigator.clipboard.read().then(clipboardItems => {
          // 检查组件状态
          if (this._isDestroyed || this._isBeingDestroyed) {
            return
          }
          
          const imageItems = clipboardItems.filter(item => 
            item.types.some(type => type.startsWith('image/'))
          )
          
          if (imageItems.length > 0) {
            const files = []
            Promise.all(imageItems.map(item => {
              return item.getType('image/png').then(blob => {
                const file = new File([blob], `clipboard_image_${Date.now()}.png`, { type: 'image/png' })
                files.push(file)
              })
            })).then(() => {
              // 检查组件状态
              if (this._isDestroyed || this._isBeingDestroyed) {
                return
              }
              
              if (files.length > 0) {
                this.uploadImages(files)
              }
            }).catch(err => {
              console.error('读取剪贴板失败:', err)
              if (!(this._isDestroyed || this._isBeingDestroyed)) {
                this.$refs.fileInput.click()
              }
            })
          } else {
            if (!(this._isDestroyed || this._isBeingDestroyed)) {
              this.$refs.fileInput.click()
            }
          }
        }).catch(() => {
          if (!(this._isDestroyed || this._isBeingDestroyed)) {
            this.$refs.fileInput.click()
          }
        })
      } else {
        if (!(this._isDestroyed || this._isBeingDestroyed)) {
          this.$refs.fileInput.click()
        }
      }
    },

    // 处理文件选择
    handleFileChange(event) {
      // 检查组件状态
      if (this._isDestroyed || this._isBeingDestroyed) {
        return
      }
      
      const files = Array.from(event.target.files)
      if (files.length > 0) {
        this.uploadImages(files)
      }
      // 清空input，允许重复选择同一个文件
      event.target.value = ''
    },

    // 上传图片
    uploadImages(files) {
      // 检查组件状态
      if (this._isDestroyed || this._isBeingDestroyed) {
        return
      }
      
      const uploadPromises = files.map(file => {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('positionDate', new Date().toISOString().split('T')[0]) // 当前日期
        formData.append('stockCode', this.stockCode)
        formData.append('stockName', this.stockName)
        
        return uploadHistoricalPosition(formData)
      })
      
      Promise.all(uploadPromises).then(responses => {
        // 检查组件状态
        if (this._isDestroyed || this._isBeingDestroyed) {
          return
        }
        
        const successCount = responses.filter(response => response.code === 200).length
        if (successCount > 0) {
          this.$message.success(`成功上传 ${successCount} 张图片`)
          this.loadPositions() // 重新加载数据
        } else {
          this.$message.error('上传失败')
        }
      }).catch(error => {
        // 检查组件状态
        if (this._isDestroyed || this._isBeingDestroyed) {
          return
        }
        
        console.error('上传图片时发生错误:', error)
        this.$message.error('上传图片时发生错误')
      })
    },

    // 查看历史持仓图片
    handleViewPosition(item) {
      if (item.imageBase64) {
        let messageBoxInstance = null
        
        // 创建简化版图片预览弹窗
        const imageHtml = `
          <div id="image-preview-container" 
               style="display: flex; align-items: center; justify-content: center; width: 100vw; height: 100vh; background-color: rgba(0,0,0,0.95); position: fixed; top: 0; left: 0; z-index: 9999; cursor: pointer;">
            <img src="${item.imageBase64}" 
                 style="max-width: 95vw; max-height: 95vh; width: auto; height: auto; object-fit: contain; pointer-events: none; box-shadow: 0 8px 32px rgba(0,0,0,0.3);" />
            <div style="position: absolute; top: 20px; right: 20px; color: #fff; font-size: 24px; opacity: 0.7; pointer-events: none;">✕</div>
          </div>
        `
        
        messageBoxInstance = this.$alert(imageHtml, `历史持仓 - ${this.formatDate(item.positionDate)}`, {
           dangerouslyUseHTMLString: true,
           showConfirmButton: false,
           showClose: true,
           customClass: 'position-image-preview-simple',
           center: true,
           closeOnClickModal: true,
           closeOnPressEscape: true,
           callback: () => {
             messageBoxInstance = null
           }
         })
         
         // 添加点击背景关闭功能
         this.$nextTick(() => {
           const messageBox = document.querySelector('.position-image-preview-simple')
           if (messageBox) {
             const content = messageBox.querySelector('.el-message-box__content')
             if (content) {
               content.style.cursor = 'pointer'
               content.addEventListener('click', (e) => {
                 if (e.target === content || e.target.tagName === 'DIV') {
                   messageBox.querySelector('.el-message-box__close').click()
                 }
               })
             }
           }
         })
      } else {
        this.$message.error('图片数据无效')
      }
    },

    // 删除单张历史持仓图片
    handleDeletePosition(item) {
      // 检查组件状态
      if (this._isDestroyed || this._isBeingDestroyed) {
        return
      }
      
      this.$confirm('确定要删除这张历史持仓图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 检查组件状态
        if (this._isDestroyed || this._isBeingDestroyed) {
          return
        }
        
        return deleteHistoricalPosition(item.id)
      }).then(response => {
        // 检查组件状态
        if (this._isDestroyed || this._isBeingDestroyed) {
          return
        }
        
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.loadPositions() // 重新加载数据
        } else {
          this.$message.error('删除失败: ' + response.msg)
        }
      }).catch(() => {
        // 用户取消删除
      })
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadPositions()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadPositions()
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleDateString('zh-CN')
    },
    
    // 格式化数字
    formatNumber(num) {
      if (num === null || num === undefined) return '0'
      return num.toLocaleString('zh-CN')
    },
    
    // 格式化货币
    formatCurrency(value, short = false) {
      if (value === null || value === undefined || value === '') return '0.00'
      const num = parseFloat(value)
      if (isNaN(num)) return '0.00'
      
      if (short && Math.abs(num) >= 1000) {
        return (num >= 0 ? '+' : '') + (num / 1000).toFixed(1) + 'k'
      }
      return (num >= 0 ? '' : '-') + Math.abs(num).toFixed(2)
    },
    
    // 设置排序顺序
    setSortOrder(order) {
      this.sortOrder = order
      this.saveSortPreferences() // 保存排序偏好
      this.showSortTip()
      this.loadPositions()
    },

    // 处理排序类型变化
    handleSortChange() {
      this.saveSortPreferences() // 保存排序偏好
      this.showSortTip()
      this.loadPositions()
    },

    // 显示排序提示
    showSortTip() {
      const sortTypeMap = {
        date: '日期',
        totalValue: '总市值',
        totalCount: '总股数'
      }
      const sortOrderMap = {
        asc: '升序',
        desc: '降序'
      }
      this.$message.success(`已按${sortTypeMap[this.sortType]}${sortOrderMap[this.sortOrder]}排序`)
      
      // 滚动到顶部
      this.$nextTick(() => {
        const container = document.querySelector('.position-images')
        if (container) {
          container.scrollTop = 0
        }
      })
    },

    // 获取排序类型标签
    getSortTypeLabel(type) {
      const labels = {
        date: '日期',
        createdTime: '创建日期',
        totalValue: '总市值',
        totalCount: '总股数'
      }
      return labels[type] || '日期'
    },

    // 保存排序偏好到本地存储
    saveSortPreferences() {
      const preferences = {
        sortType: this.sortType,
        sortOrder: this.sortOrder
      }
      localStorage.setItem('historicalPositionSortPreferences', JSON.stringify(preferences))
    },

    // 重置排序到默认值
    resetSort() {
      this.sortType = 'date'
      this.sortOrder = 'desc'
      this.saveSortPreferences()
      this.$message.success('已重置为默认排序（日期降序）')
      this.loadPositions()
    },

    // 从本地存储加载排序偏好
    loadSortPreferences() {
      const saved = localStorage.getItem('historicalPositionSortPreferences')
      if (saved) {
        try {
          const preferences = JSON.parse(saved)
          this.sortType = preferences.sortType || 'date'
          this.sortOrder = preferences.sortOrder || 'desc'
        } catch (error) {
          console.warn('加载排序偏好失败:', error)
        }
      }
    },

    // 设置键盘快捷键
    setupKeyboardShortcuts() {
      document.addEventListener('keydown', this.handleKeyDown)
    },

    // 处理键盘事件
    handleKeyDown(event) {
      // 防止在输入框中触发
      if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
        return
      }

      // Ctrl/Cmd + 数字键切换排序类型
      if (event.ctrlKey || event.metaKey) {
        switch (event.key) {
          case '1':
            event.preventDefault()
            this.sortType = 'date'
            this.handleSortChange()
            break
          case '2':
            event.preventDefault()
            this.sortType = 'totalValue'
            this.handleSortChange()
            break
          case '3':
            event.preventDefault()
            this.sortType = 'createdTime'
            this.handleSortChange()
            break
          case '4':
            event.preventDefault()
            this.sortType = 'totalCount'
            this.handleSortChange()
            break
          case 'ArrowUp':
            event.preventDefault()
            this.setSortOrder('asc')
            break
          case 'ArrowDown':
            event.preventDefault()
            this.setSortOrder('desc')
            break
        }
      }
    }
  }
}
</script>

<style scoped>
.historical-position-container {
  padding: 20px;
}

.position-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.sort-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
}

.sort-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.sort-status {
  margin-left: 10px;
  display: flex;
  align-items: center;
}

.position-images {
  min-height: 400px;
}

/* 确保 el-col 有间隔 - 使用更具体的选择器 */
.position-images .el-row .el-col {
  padding-left: 40px !important;
  padding-right: 40px !important;
  margin-bottom: 50px !important;
}

/* 覆盖Element UI的负边距 */
.position-images .el-row {
  margin-left: -40px !important;
  margin-right: -40px !important;
}

.position-image-card {
  position: relative;
  border: 2px solid #dcdfe6;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  margin-bottom: 60px;
  min-width: 240px;
  width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  background-color: #ffffff;
}

.position-image-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.position-image {
  width: 100%;
  height: 240px;
  display: block;
  object-fit: contain;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.image-error {
  width: 100%;
  height: 240px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.image-error i {
  font-size: 48px;
  margin-bottom: 10px;
}

.position-image-info {
  padding: 12px;
  background-color: #f8f9fa;
}

/* 图片加载占位符 */
.position-image ::v-deep(.el-image__placeholder) {
  background: linear-gradient(90deg, #f0f2f5 25%, #e6e8eb 50%, #f0f2f5 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

.info-date {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.info-stats {
  margin-bottom: 12px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  font-size: 13px;
}

.stat-item:last-child {
  margin-bottom: 0;
}

.stat-label {
  color: #909399;
  font-weight: 400;
}

.stat-value {
  color: #303133;
  font-weight: 500;
}

.profit-positive {
  color: #67c23a !important;
}

.profit-negative {
  color: #f56c6c !important;
}

.info-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.position-pagination {
  margin-top: 20px;
  text-align: center;
}

.position-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.position-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.position-content {
  min-height: 400px;
}

  /* 排序按钮动画 */
  .sort-controls .el-button {
    transition: all 0.3s ease;
  }
  
  .sort-controls .el-button:hover {
    transform: translateY(-1px);
  }
  
  .sort-controls .el-button:active {
    transform: scale(0.95);
  }
  
  /* 排序选择器动画 */
  .sort-controls .el-select {
    transition: all 0.3s ease;
  }
  
  .sort-controls .el-select:hover {
    transform: translateY(-1px);
  }
  
  /* 排序按钮图标动画 */
  .sort-controls .el-icon-sort-up,
  .sort-controls .el-icon-sort-down {
    transition: transform 0.3s ease;
  }
  
  .sort-controls .el-button:hover .el-icon-sort-up,
  .sort-controls .el-button:hover .el-icon-sort-down {
    transform: scale(1.2);
  }
  
  /* 帮助图标动画 */
  .sort-controls .el-icon-question {
    transition: transform 0.3s ease;
  }
  
  .sort-controls .el-icon-question:hover {
    transform: scale(1.1) rotate(10deg);
  }
  
  /* 重置按钮图标动画 */
  .sort-controls .el-icon-refresh {
    transition: transform 0.3s ease;
  }
  
  .sort-controls .el-button:hover .el-icon-refresh {
    transform: rotate(180deg);
  }
  
  /* 排序状态标签动画 */
  .sort-status .el-tag {
    animation: fadeInScale 0.3s ease;
  }
  
  @keyframes fadeInScale {
    0% {
      opacity: 0;
      transform: scale(0.9);
    }
    100% {
      opacity: 1;
      transform: scale(1);
    }
  }

  /* 图片预览弹窗样式 - 极简设计 */
  :deep(.position-image-preview-simple) {
    width: 95vw !important;
    max-width: 95vw !important;
    height: 95vh !important;
    max-height: 95vh !important;
    margin: 0 !important;
    border-radius: 0 !important;
    background-color: #000 !important;
    box-shadow: none !important;
  }

  /* 隐藏标题栏 */
  :deep(.position-image-preview-simple .el-message-box__header) {
    display: none !important;
  }

  /* 内容区域全屏 */
  :deep(.position-image-preview-simple .el-message-box__content) {
    margin: 0 !important;
    padding: 0 !important;
    width: 100% !important;
    height: 100% !important;
  }

  /* 消息区域全屏 */
  :deep(.position-image-preview-simple .el-message-box__message) {
    margin: 0 !important;
    padding: 0 !important;
    width: 100% !important;
    height: 100% !important;
  }

  /* 关闭按钮样式 */
  :deep(.position-image-preview-simple .el-message-box__close) {
    display: none !important;
  }
</style>